Skip to content

fix(#986): order MCP tool sets by turn so a late drop or check never overwrites a newer one - #1004

Merged
scuttletoby merged 4 commits into
mainfrom
fix/986-mcp-toolsets
Nov 22, 2026
Merged

scuttletoby merged 4 commits into
mainfrom
fix/986-mcp-toolsets

Conversation

@scuttletoby

@scuttletoby scuttletoby commented Nov 22, 2026 •

Copy link
Copy Markdown
Owner

Fixes #986

One fix covers the three race points, as the issue suggested. Each turn draws a place (nextT3ToolSetTurn) as its check starts, before it reads the profile. Every fixed set keeps the turn that fixed it. A late check, a stopped turn's forget, or a timed-out hold's drop writes only if no later turn has fixed the thread's set. A hold remembers the latest turn that took or joined it. Its drop writes Refused for that turn, so that turn's own late check still replaces the refusal, but an older turn's check does not.

Callers that fix sets now pass their turn: the Codex turn/start check, the Codex turn/started watch (the hold and the profile step share one turn), the turn check before a provider call (mcpProfileTurnCheck.ts), and the Claude plan (its refusals, the same-key fix, and the fix when the options are read).

Point Fix Test (red on main → green)
mcpT3ToolSets.ts drop overwrites a newer turn's set: a joining turn fixed its set while the first turn's check is stuck The hold tracks its latest turn; the drop leaves a set fixed by that turn or a later one and only removes the hold codexMcpProfile.test.ts "a joining turn fixed its set while the first is stuck: the drop keeps it" (red: expected true to be false, the drop wrote Refused)
Same point: a turn T3 starts itself does not touch the hold Its turn is later than the hold's, so the drop leaves its set codexMcpProfile.test.ts "a turn T3 starts itself while a Codex turn's hold is stuck: the drop keeps its set" (red: same)
codexMcpProfile.ts two checks finish out of order; the last one to finish wins, so a late check can widen the set profileStep fixes with the turn drawn before the read; an older turn's late fix is ignored codexMcpProfile.test.ts "two checks finishing out of order: the later turn's set stands" (red: expected 'Groups' to deeply equal ['waits'], widened back to all); mcpProfileTurnCheck.test.ts "two turns' checks finishing out of order" (red: same, on the pre-call check)
A check fixed its set but has not released its hold when a request's wait ends: Refused is written over the new set The drop sees the hold's own turn (or a later one) has fixed a set and leaves it mcpT3ToolFilter.test.ts "a check fixed its set but has not released yet as the bound passes: its set stands" (red: the request got false/Refused); "the hold's own turn fixes its set as the bound passes" (same turn exactly)
claudeMcpProfile.ts the "never wider" plan-key check has no test of its own Added __testing.clearOpenedPlanKeys (plus keepOpenedPlanKey, hasOpenedPlanKey); the two tests that relied on keys left by earlier tests now start empty claudeMcpProfile.test.ts "never wider: a process opened with one plan meets a different, wider one". The code was already right, so the red is a mutation check: with the comparison cut down to openedPlanKeys.has(...), this test fails (expected ['threads','orchestration'] to equal 'Refused') and the 55 tests that were already there all pass
claudeMcpProfile.ts the 4096 cap drops the process opened first, not the one used longest ago A plan that matches the opened key refreshes that entry (LRU) claudeMcpProfile.test.ts "the cap drops the thread whose process was used longest ago" (red: expected false to be true, the thread in use was dropped)

State questions, with tests:

  • Runs again: after an out-of-order pair, the next turn fixes its set as usual (Codex test). After a refusal, the same plan gets its set back (Claude "never wider" test). After a drop, a later hold starts fresh (existing test, still green).
  • Stops half-way: an older turn that stopped half-way no longer clears a newer turn's set (mcpProfileTurnCheck.test.ts "stopped half-way after a later turn fixed its set", red: expected undefined). A turn's own stop still clears its set. After that stop, an older turn's late check still writes nothing, and a request's remembered set or a later turn still writes (mcpT3ToolFilter.test.ts unit tests). A check interrupted mid-way still releases its hold (existing test).
  • Old/empty/unreadable state: with no entry after a restart, any check writes (unit test "empty state (after a restart)"); the turn counter, sets, holds and plan keys are all in memory and reset together. When the hold's check never fixes a set, the drop still writes Refused, and that check's late set then replaces it (Codex test, fails closed). With no opened key, a plan fixes nothing until its process opens (Claude test). A profile that cannot be read still fixes Refused for its own turn (existing tests).

The new unit tests for the turn API (nextT3ToolSetTurn, forgetT3ToolSet(id, turn)) are red on main with nextT3ToolSetTurn is not a function, since the API is new. Every other red above is a behavioral assertion failure.

Checks run (first push): the 4 changed test files one at a time (mcpProfileTurnCheck 30, mcpT3ToolFilter 25, codexMcpProfile 53, claudeMcpProfile 57, all passed), plus fmt:check, lint (0 errors), and the apps/server typecheck.

Left

  • Requests still wait out a stuck hold. A request waiting on a stuck hold still waits until the hold's bound (≤10 s), even when a later turn (T3's own, or a joiner) has already fixed its set. It then gets that set, not Refused. Ending the hold early when a newer turn fixes a set would shorten the wait, but the issue asks only that the newer set not be overwritten, and the wait already fails closed. I did not change it.
  • A joining turn keeps the first turn's bound. The issue names this as part of the cause; I did not extend the bound. If the joining turn's check is still running when the first turn's bound passes, its requests get Refused until its own check fixes the set. That check's late set then replaces the refusal (same turn), so nothing newer is lost. Extending the bound per joiner is a separate trade-off between wait time and closing early. That is an owner call.

Round 1

Both lenses said safe to merge. Minors handled per the round rule (fixed here when small and in scope, else dropped with a reason). Merged origin/main first.

Finding Fix, or why dropped Test
State 1: the joiner bump held.turn = Math.max(held.turn, turn) in holdT3ToolSet has no test Test added mcpT3ToolFilter.test.ts "a joined turn still checking as the bound passes: the first's late check cannot widen" (turn A holds, turn B joins, B still checking at the bound, A's late wide check writes nothing, B's replaces the refusal). Red with the line removed: expected 'Groups' to be 'Refused' (A's wide set written)
Code 1 / state 3: fixT3ToolSet and holdT3ToolSet default turn to nextT3ToolSetTurn() turn is now required on both. Every production caller already passed the turn drawn before its profile read; tests now draw it themselves Typecheck: a call without a turn no longer compiles
State 2 (was Left 3): after a thread is dropped at the 4096 cap, an older turn's late check can replace the newer, narrower set mcpT3ToolSets.ts remembers the latest turn dropped at the cap (droppedTurn) and uses it, not 0, for a thread with no entry (in newest, rememberT3ToolSet and the hold drop). A too-old check then writes nothing and the next request works the set out from the settings mcpT3ToolFilter.test.ts "keeps at most MAX_T3_TOOL_SETS threads, dropping the oldest" (extended: older late check after the drop writes nothing, nor over a request's set; a later turn writes). Red without the remembered turn: expected { name: 'older' } to be undefined
Code 2: __testing hooks such as keepOpenedPlanKey importable by production code Dropped: no existing rule can refuse it. no-restricted-imports cannot see X.__testing through a namespace import (the repo's convention), and a new oxlint rule would mean changing the shared lint plugin and vite.config.ts, which is outside this PR. No non-test file uses another module's __testing today (grep) none
Code 3: the new Codex #986 tests wait a real 20 ms (settle) Removed settle. A gated check's end is awaited via the hold's done, which completes when every check holding it releases, after its fix. Checks whose profile read is not gated run inside emit (forked with startImmediately), so there is nothing to wait for The 4 Codex #986 tests. They still go red (3 of them) with newest forced to true, so the latch does wait for the late check
State 4 / Left 2: joiners share the first turn's bound Unchanged, as asked: owner call. The state lens recommends keeping it (bounded wait, fails closed) the new joiner test covers why it is safe

State questions for the round-1 code:

  • Runs again: a later turn draws a higher number than any dropped one and writes as usual (cap test, last step).
  • Stops half-way: unchanged. forgetT3ToolSet and the drop use the same "latest fixed turn" check, now aware of the cap.
  • Empty cache: after a restart droppedTurn is 0 with everything else, so any check writes, as before. __testing.clear resets it too.
  • The cap: a dropped thread keeps its order through droppedTurn. That is one number for all threads, so a brand-new thread's check drawn before a later drop also writes nothing. Its requests then work the set out from the current settings (never wider than they allow), and its next turn writes as usual.

Round-1 checks: the 4 changed test files one at a time. codexMcpProfile 53, mcpProfileTurnCheck 30, claudeMcpProfile 57: all passed. mcpT3ToolFilter: 15 passed (every in-memory test, including the new and extended ones); its 11 socket tests could not run on the machine used (connections to 127.0.0.1 are blocked there, ConnectTimeoutError), so CI runs them. vp run check:changed: format, lint (after trimming one comment), knip, graphql and typecheck pass; its test step fails only on those same 11 socket tests.

General vs project

  • General: when several async checks write one shared slot, give each a monotonic ticket at its start and write only if no later ticket has written (also for clears and timeout fallbacks). Don't use "last to finish wins". A bounded "recently used" cache must refresh its entry on a hit, not only on insert. Module-global state needs a test reset hook, so a test cannot pass only because an earlier test left state behind.
  • Project: each T3 tool set write in mcpT3ToolSets.ts (fix, forget, remember, drop) carries the turn it is for. New callers draw it with nextT3ToolSetTurn() before they read the profile.

🤖 Generated with Claude Code

…overwrites a newer one

Each turn draws a place as its check starts; a fixed set keeps the turn that
fixed it. A late check, a stopped turn's forget, or a timed-out hold's drop
writes only if no later turn has fixed the thread's set. The drop stands for
the hold's latest turn, so that turn's own late check still replaces it.

Claude: a plan that matches the process's opened key refreshes it, so the
4096 cap drops the thread used longest ago, and the opened keys get a test
reset hook with a test of their own for the "never wider" comparison.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@scuttletoby

Copy link
Copy Markdown
Owner Author

lens: code · reviewer: lens agent (Opus 5.5) · read at: 980f15a
covered: the full diff (mcpT3ToolSets.ts, codexMcpProfile.ts, claudeMcpProfile.ts, mcpProfileTurnCheck.ts and the 4 test files), the T3 tool rule that reads the sets and drops holds (mcpT3ToolRule.ts setFor/workedOut), how ClaudeAdapterV2 reads the plan options, issue #986 with its comment, #961 for context, the PR body
checks: ran the 4 changed test files one at a time on this head (mcpT3ToolFilter 25, mcpProfileTurnCheck 30, codexMcpProfile 53, claudeMcpProfile 57: all pass). Undid each fix and re-ran: (1) newest always true (last to finish wins): 3 codexMcpProfile and 2 mcpProfileTurnCheck #986 tests fail; (2) the drop's turn check removed: 2 codexMcpProfile and 2 mcpT3ToolFilter #986 tests fail; (3) the LRU refresh on a same-key plan removed: the claudeMcpProfile cap test fails; (4) the never-wider check cut to openedPlanKeys.has(...): the claudeMcpProfile never-wider test fails. All "fails without" claims hold.
state: runs again: the next turn draws a higher number and writes as usual; a same-turn rewrite (refusal then set, plan fix then options fix) is allowed by <=. Stops half-way: an interrupted pre-call check forgets only when no later turn wrote, and leaves its turn on the empty slot, so an older late check still cannot write; a request may still remember a set there. Old/empty state: no entry means turn 0, so any check writes; a restart clears sets, holds, plan keys and the counter together, so no stale order survives. Order is lost only when a thread is dropped at the 4096 cap (named under "Left").
blocker: none
major: none
minor: fixT3ToolSet and holdT3ToolSet default turn to nextT3ToolSetTurn() (apps/server/src/fork/mcpT3ToolSets.ts:77, :135). No production caller uses the default today (every caller passes its turn, checked by grep), but a future caller that leaves it out draws its number at write time, outranks every check already in flight, and brings back "last to finish wins" without a type error. Making turn required (tests pass nextT3ToolSetTurn() themselves) closes that.
minor: __testing in apps/server/src/fork/claudeMcpProfile.ts:742 exports keepOpenedPlanKey, which marks a plan key as opened; a production import of it would let a wider plan fix its set without a process opening. No non-test file imports it (same convention as the __testing in mcpT3ToolSets.ts and mcpT3ToolRule.ts); a lint rule against __testing imports outside *.test.ts would make that enforced rather than trusted. Can be a follow-up.
minor: the new Codex tests let fibers run with settle = TestClock.withLive(Effect.sleep("20 millis")) (apps/server/src/fork/codexMcpProfile.test.ts:1504): a real 20 ms wait on a loaded runner may end before the check fiber writes, so the "stands" assertions could pass or fail by timing. Awaiting a Deferred the scripted profile read completes (as reached already does) would make them deterministic.

Points checked with no finding:

  • The turn is drawn before the profile read on every path: Claude planFor (before profileFor), the pre-call check (before profileFor), Codex turn/start (before profileStep) and turn/started (before the hold and the profile step, which share it).
  • Each write checks "no later turn wrote" and writes in one synchronous step (fixT3ToolSet, forgetT3ToolSet, dropT3ToolSetHold run inside Effect.sync or plain code), so there is no await between the check and the write.
  • The drop writes Refused as held.turn, the max of every turn that took or joined the hold, so only the newest member's late check can replace it.
  • Claude: the options getter's fix can now lose to a later turn's number, but the adapter reads mcpProfile.options in the same turn flow that made the plan, so a later turn's plan cannot come in between on the same thread.
  • LRU: keep and keepOpenedPlanKey delete then set (Map insertion order), eviction walks from the oldest and stops at the cap: O(1) amortized. Reads do not refresh sets, which is fine since every turn writes its thread's entry.
  • Claude and Codex both pass their turn to every fix; children and goal-only paths draw no turn and fix nothing, as before.

verdict: safe to merge

🤖 Generated with Claude Code

@scuttletoby

Copy link
Copy Markdown
Owner Author

lens: state · reviewer: lens agent (Opus 5.5, independent of the other lens) · read at: 980f15a
verdict: safe to merge
covered: the full diff (mcpT3ToolSets.ts, codexMcpProfile.ts, mcpProfileTurnCheck.ts, claudeMcpProfile.ts and the 4 test files), every caller of the tool set API (mcpT3ToolRule.ts setFor / workedOut / searchable), #986 with the owner's comment, the PR body.
checks: ran the 4 changed test files one at a time: mcpT3ToolFilter 25, mcpProfileTurnCheck 30, codexMcpProfile 53, claudeMcpProfile 57, all passed. Mutations: newest() always true turns 2 unit tests and 3 Codex tests red; removing the drop's turn check (mcpT3ToolSets.ts:190) turns 2 hold tests and 2 Codex tests red; removing the joiner bump (mcpT3ToolSets.ts:149) turns NOTHING red (minor 1). Two scratch tests (not pushed) for minor 1 and minor 2, both behave as described below.
state: runs again: the same turn writing twice is allowed (<=) and only ever writes its own read; a second check of one turn draws a later number, so the later read wins. Turn numbers are drawn before every profile read (Claude plan, pre-call check, Codex turn/start, Codex turn/started), and an older write is blocked only by a newer WRITE, never by a number drawn that never writes, so nothing gets stuck on an old wide set. Stopped half-way: forget writes "no set" at its own turn; an older late check cannot fill it, a request's fresh read or any later turn can. A turn stopped between drawing its number and fixing has written nothing, so it blocks nothing. A hold that times out writes Refused at the hold's latest turn (fails closed) and that turn's own late check replaces it. A drop that returns false now deletes the hold first, so setFor's retry cannot loop. Restart: sets, holds, plan keys and the counter are all in memory and reset together; checks in flight die with the process, so no old turn survives to write. Old state: there is no stored state from before this change (memory only); a missing entry counts as turn 0, so any check writes, which is the old behaviour. Counter: one module-wide counter for all threads, Claude and Codex alike; only the order inside one thread is compared, so sharing it is fine; a JS number does not wrap in practice (2^53).
blocker: none
major: none
minor: 1. The joiner bump held.turn = Math.max(held.turn, turn) (apps/server/src/fork/mcpT3ToolSets.ts:149) guards against a wider set but no test covers it. Case: turn A's check read the wide profile and is stuck, turn B joined after the profile was narrowed and its check is still running when the bound passes. With the line, the drop writes Refused at B, so A's late check cannot write. Without it, the drop writes at A, A's late check then writes A's wide set, and it stands until B's check finishes (forever, if B's is stuck too). A scratch test of exactly this is green on this head and red with the line removed. Please add it (unit level is enough: hold A, hold B, drop, late fix at A, expect Refused).
minor: 2. Left 3, answered: after a thread is dropped at the 4096 cap (mcpT3ToolSets.ts:57-67), an older turn's late check CAN write a set wider than the newer turn's profile allows. It is the set the older turn was allowed when it started, not wider than any profile ever was, but it replaces the newer, narrower one for the running turn (scratch test: fix narrow at the newer turn, fill the cap, a request remembers narrow, the older late check writes all, and all stands). It needs 4096 other threads written while one check is still running, so it is far-fetched. A cheap close: keep the highest turn ever evicted and use it instead of 0 for a missing entry in newest(); a too-old check then writes nothing and the next request works the set out from the settings. Fine as a follow-up.
minor: 3. fixT3ToolSet and holdT3ToolSet still default turn to nextT3ToolSetTurn() (mcpT3ToolSets.ts:77, :135). No production caller uses the default now, but a future caller that reads the profile and then fixes without a turn gets a number drawn AFTER its read, so a stale read counts as the newest. Make turn required (the tests that use the default would pass an explicit turn).
minor: 4. Left 2 (joiners share the first turn's deadline), owner decision. Recommendation: keep it as is. The wait stays bounded at 10 s, a joiner still running at the bound gets Refused (fails closed), and its own late set replaces the refusal; extending the bound per joiner would let a stream of Codex turns hold requests without end. Minor 1's test is what keeps this choice safe.

🤖 Generated with Claude Code

…ap, latched Codex tests

- fixT3ToolSet and holdT3ToolSet take the turn as a required argument: a caller can no longer
  draw its number at write time and rank a stale read newest.
- Remember the latest turn dropped at the 4096 cap and use it for a thread with no entry, so an
  older turn's late check cannot replace a newer, narrower set after the drop.
- Test the joiner bump in holdT3ToolSet: a joined turn still checking as the bound passes keeps
  the first turn's late (wide) check from writing.
- The Codex #986 tests await the hold's done (released after each check's fix) instead of a real
  20 ms wait.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@scuttletoby

Copy link
Copy Markdown
Owner Author

not a lens: narrow check after fix round 1

Verdict: SAFE TO MERGE (head a235326598774d1ec482b9d9e8211a4ee37b1a81; round-1 diff checked as bc44b630e4..a235326598, so the origin/main merge is left out). I found one new minor (1b). It does not block.

1. Fix 3 (droppedTurn)

  • No path writes a wider set. droppedTurn only raises the bar for writing. A thread with no entry is now treated as last fixed at droppedTurn instead of 0 (apps/server/src/fork/mcpT3ToolSets.ts:75). So fixT3ToolSet (:85), forgetT3ToolSet (:93) and the time-limit drop (:192) each write in fewer cases than before, never in more. A late check older than any dropped turn writes nothing (:78).

    • When the drop declines, the rule looks again (mcpT3ToolRule.ts:199-204). The hold was already deleted (mcpT3ToolSets.ts:191), so the request works the set out fresh from the settings (mcpT3ToolRule.ts:160-168). That never loops.
    • A Refused result is never remembered (:171-176).
  • The next turn really writes. droppedTurn is always the turn of a stored entry, so it is never above lastTurn. A newly drawn turn is therefore always higher and writes. Both the cap test's last step and my scratch case below confirm this.

  • The max only grows. Math.max at :69 is the only write, apart from __testing.clear (:202).

  • Restart or missing value. droppedTurn starts at 0 together with the sets, holds and turn counter, all in memory, so a restart behaves exactly as it does on main. The value is a plain number that cannot be undefined.

  • 1b, minor and new in round 1 (scratch-tested, then reverted): the statement "a new thread's requests use the current settings" does not cover a request whose settings read was already in flight. Scenario:

    1. A request for new thread Z starts reading the profile (still wide).
    2. The profile is narrowed.
    3. Z's turn check draws turn t and reads the narrow profile.
    4. More than 4096 other set writes push droppedTurn above t.
    5. Z's check writes nothing (:85).
    6. The in-flight request finishes and rememberT3ToolSet keeps the wide read at turn droppedTurn (:107).

    Z then runs turn t with the wide set until its next turn, which does write. Before round 1, step 5 wrote the narrow set and step 6 returned it. The wide set was allowed when it was read, it lasts at most one turn, and it needs cap churn during a single profile read. Possible follow-up: give the request its own turn, drawn before its read, and remember only when that turn is newest.

2. Red without the change (undone and run here)

  • With the joiner line held.turn = Math.max(held.turn, turn) removed (:152), mcpT3ToolFilter.test.ts:845 fails (expected 'Groups' to be 'Refused'), 1 failed / 25 passed.
  • With lastFixed using ?? 0 instead of ?? droppedTurn (:75), mcpT3ToolFilter.test.ts:640 fails (expected { name: 'older' } to be undefined), 1 failed / 25 passed.
  • Both pass again with the change restored.

3. Fix 2: every production caller passes a turn drawn before its profile read

  • git grep finds callers in only 3 non-test files:
    • Claude: claudeMcpProfile.ts:784 draws the turn before profileFor at :787. The refusals (:789, :795), the same-key fix (:806) and fixedWhenOpened (:767) all use that turn.
    • Pre-call check: mcpProfileTurnCheck.ts:97 draws before :98, and is used at :100, :103 (forget) and :105.
    • Codex turn/start: codexMcpProfile.ts:454 draws before profileStep at :455, which fixes at :379 and :384.
    • Codex turn/started: :578 draws before the hold at :587 and profileStep, which share one turn.
  • turn is now required at mcpT3ToolSets.ts:85 and :139.

4. Fix 5: Codex tests

  • No settle or real-time sleep is left in the MCP tool sets: newer turn's set can be overwritten by a late drop or late check (#961 follow-up) #986 block (codexMcpProfile.test.ts:1481-1623). It now waits on the hold's done (:1509).
    • Four TestClock.withLive(Effect.sleep("20 millis")) calls remain at :1225, :1288, :1299 and :1367. They are in older tests that this PR did not add.
  • With newest forced to true, 3 of the 4 tests fail (:1520, :1547, :1575, each expected 'Groups' to deeply equal ['waits']).
  • The 4th (:1599, "a hold whose check never fixes a set") still passes under that change, because the only late write it checks is the hold's own turn. Allowing every write does not change that outcome. It is still a useful test: it is the fail-closed check, and it fails with newest changed to < (own turn blocked) and with the drop's Refused write removed (:194). I ran both.

5. Dropped item 4 (__testing hooks)

  • The reason is true. eslint/no-restricted-imports (vite.config.ts:304 and the later entries) only sees import specifiers, so it cannot see X.__testing reached through import * as X, which is how the tests import these modules.
  • git grep finds no .__testing use and no __testing import in any non-test file.

Runs here (one at a time, from a fresh install):

  • mcpT3ToolFilter.test.ts: 26/26 passed, including all 11 socket tests (none skipped).
  • codexMcpProfile.test.ts: 53/53.
  • mcpProfileTurnCheck.test.ts: 30/30.
  • claudeMcpProfile.test.ts: 57/57.

All scratch edits were reverted and the temp worktree removed.

fork-ci-result: pass on a235326598. No checks are failing or pending.

🤖 Generated with Claude Code

@scuttletoby
scuttletoby merged commit c0de9c5 into main Nov 22, 2026
38 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

MCP tool sets: newer turn's set can be overwritten by a late drop or late check (#961 follow-up)

1 participant